package com.shi.yibanjia.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class TengxunLocationUtil {

    private static final String key = "HGQBZ-4PPKL-FJ6PQ-EVYIC-U4E37-XNFEF";

    private static RestTemplate restTemplate = new RestTemplate();

    // https://apis.map.qq.com/ws/direction/v1/driving/?from=39.915285,116.403857&to=39.915285,116.803857&waypoints=39.111,116.112;39.112,116.113&output=json&callback=cb&key=[你的key]

    /**
     * 计算两个经纬度之间驾车实际行驶的公里数
     * 返回单位：公里
     *
     * @param srcLatitude
     * @param srcLongitude
     * @param descLatitude
     * @param descLongitude
     * @return
     */
    public static Double getDistanceByDriving(String srcLatitude, String srcLongitude, String descLatitude, String descLongitude) {
        String requestStr = "https://apis.map.qq.com/ws/direction/v1/driving/?from=%s,%s&to=%s,%s&output=json&key=%s";
        requestStr = requestStr.formatted(srcLatitude, srcLongitude, descLatitude, descLongitude, key);
        System.out.println(requestStr);
        String object = restTemplate.getForObject(requestStr, String.class);
        JSONObject jsonObject = JSONUtil.parseObj(object);
        return jsonObject.getByPath("result.routes[0].distance", Double.class) / 1000;
    }
}
